const {v4: uuidv4} = require('uuid')
const Notifications = require('../../models/notifications')

const getNotificationsHandler = async (_, res) => {
  try {
    const notifications = await Notifications.find()
    notifications.length
      ? res.status(200).json(notifications)
      : res.status(404).json({success: false, msg: 'Документы не найдены'})
  } catch (e) {
    res.status(500).json({success: false, msg: e})
  }
}

const postNewNotificationHandler = async (req, res) => {
  const notifications = req.body
  const notificationsWithId = notifications.map((item) => ({...item, id: uuidv4()}))
  try {
    const result = await Notifications.create(notificationsWithId)
    res.status(200).json(result)
  } catch (e) {
    res.status(500).json({success: false, msg: e})
  }
}

const patchNotificationHandler = async (req, res) => {
  const {notifications, updateFields} = req.body

  if (notifications.length) {
    try {
      const bulkOps = notifications.map((item) => ({
        updateOne: {
          filter: {id: item.id},
          update: {$set: {...updateFields}},
        },
      }))

      const result = await Notifications.bulkWrite(bulkOps)
      const updatedNotifications =
        result && result.modifiedCount > 0
          ? notifications.filter((id, index) => result.modifiedCount > index)
          : []
      res.status(200).json(updatedNotifications)
    } catch (e) {
      res.status(500).json({success: false, msg: e})
    }
  }
}

module.exports = {getNotificationsHandler, postNewNotificationHandler, patchNotificationHandler}
